{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 作业7\n",
    "(编写程序，列出指定文件夹下所有文件内容相同的文件名）\n",
    "### 通义千问:\n",
    "将C:\\python作业\\作业7下所有文件内容相同的文件名显示出来"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "找到以下重复的文件：\n",
      "文件名: zy - 副本 (4).xlsx 与 文件名: zy - 副本 (2).xlsx 内容相同\n",
      "文件名: zy - 副本 (5).xlsx 与 文件名: zy - 副本 (2).xlsx 内容相同\n",
      "文件名: zy - 副本 (6).xlsx 与 文件名: zy - 副本 (2).xlsx 内容相同\n",
      "文件名: zy - 副本 (7).xlsx 与 文件名: zy - 副本 (2).xlsx 内容相同\n",
      "文件名: zy.xlsx 与 文件名: zy - 副本 (2).xlsx 内容相同\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import hashlib\n",
    "\n",
    "def file_as_bytes(file_path):\n",
    "    \"\"\"将文件内容转换为bytes以便进行哈希处理\"\"\"\n",
    "    with open(file_path, 'rb') as file:\n",
    "        return file.read()\n",
    "\n",
    "def find_duplicate_files(directory):\n",
    "    \"\"\"查找给定目录下的重复文件\"\"\"\n",
    "    files_hashes = {}\n",
    "    duplicates = []\n",
    "\n",
    "    for root, _, filenames in os.walk(directory):\n",
    "        for filename in filenames:\n",
    "            file_path = os.path.join(root, filename)\n",
    "            file_hash = hashlib.md5(file_as_bytes(file_path)).hexdigest()\n",
    "\n",
    "            if file_hash in files_hashes:\n",
    "                # 如果已经存在，则添加到重复列表中\n",
    "                duplicates.append((filename, files_hashes[file_hash]))\n",
    "            else:\n",
    "                # 否则，将文件哈希和路径存储起来\n",
    "                files_hashes[file_hash] = filename\n",
    "\n",
    "    return duplicates\n",
    "\n",
    "# 定义目录路径\n",
    "directory_path = r'C:\\python作业\\作业7'\n",
    "\n",
    "# 查找重复文件\n",
    "duplicates = find_duplicate_files(directory_path)\n",
    "\n",
    "# 显示结果\n",
    "if duplicates:\n",
    "    print(\"找到以下重复的文件：\")\n",
    "    for dup in duplicates:\n",
    "        print(f\"文件名: {dup[0]} 与 文件名: {dup[1]} 内容相同\")\n",
    "else:\n",
    "    print(\"没有找到内容相同的文件。\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
